package com.glela.api.upload.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 序列化 工具
 * 
 * @author liujie
 */
public final class SerializeUtil
{

	private static Logger log = LoggerFactory.getLogger(SerializeUtil.class);

	/**
	 * byte[] 转 obj
	 * 
	 * @param bs
	 * @return
	 */
	public static Object deserializeToObject(byte[] bs)
	{
		ByteArrayInputStream bis = new ByteArrayInputStream(bs);
		ObjectInput in = null;
		Object o = null;
		try {
			in = new ObjectInputStream(bis);
			o = in.readObject();
		}
		catch (ClassNotFoundException e) {
			SerializeUtil.logDeserializeException(e);
		}
		catch (IOException e) {
			SerializeUtil.logDeserializeException(e);
		}
		finally {
			if (in != null) {
				try {
					in.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != bis) {
				try {
					bis.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return o;
	}

	public static byte[] serializeToByteArray(Object o)
	{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutput out = null;
		byte[] bs = null;
		try {
			out = new ObjectOutputStream(bos);
			out.writeObject(o);
			bs = bos.toByteArray();
		}
		catch (IOException e) {
			log.error("serialize " + o.getClass().getName() + " to byte array failed :" + e);
		}
		finally {
			if (out != null) {
				try {
					out.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != bos) {
				try {
					bos.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return bs;
	}

	private static void logDeserializeException(Exception e)
	{
		log.error("deserialize byte array to object failed, due to: " + e.getMessage());
	}

	private SerializeUtil()
	{
	}

}
